//
//  HMComposeTextView.swift
//  Weibo22
//
//  Created by Apple on 16/12/9.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

//  自定义textView
class HMComposeTextView: UITextView {
    
    //  MARK: -- 懒加载
    private lazy var placeHolderLabel: UILabel = {
        
        let label = UILabel()
        label.text = "听说下雨天音乐跟辣条更配哟~"
        label.font = UIFont.systemFont(ofSize: 12)
        
        label.textColor = UIColor.lightGray
        //  多行显示
        label.numberOfLines = 0
        
        return label
        
    }()
    
    //  设置站位文字
    var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    //  设置textView的font属性的时候让占位label的font和textView的font同步
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font!
            }
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        //  监听文字改变的通知
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        
        
        addSubview(placeHolderLabel)
        //  使用手写方式布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 8))
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        
    }
    
    
    @objc private func textChange() {
        //  占位文字是否显示取决与是否有内容
        placeHolderLabel.isHidden = hasText
    
    }
    
    
    deinit {
        //  移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
    
    
   

}
